#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/epoll.h>
#include <unistd.h>
#include <sys/types.h>

#define IPADDRESS "127.0.0.1"
#define PORT 6666
#define MAXSIZE 1024
#define LISTENQ 5
#define FDSIZE 1000
#define EPOLLEVENTS 100

/*函数声明*/
/*创建套接字并进行绑定*/
int socket_bind(const char *ip, int port);
/*IO多路复用epoll*/
void do_epoll(int listenfd);
/*事件处理函数*/
void handle_events(int epollfd, struct epoll_event *events, int num, int listenfd, char *buf);
/*处理接收到的连接*/
void handle_accpet(int epollfd, int listenfd);
/*读处理*/
void do_read(int epollfd, int fd, char *buf);
/*写处理*/
void do_write(int epollfd, int fd, char *buf);
/*添加事件*/
void add_event(int epollfd, int fd, int state);
/*修改事件*/
void modify_event(int epollfd, int fd, int state);
/*删除事件*/
void delete_event(int epollfd, int fd, int state);

int main(int argc, char *argv[])
{
    int listenfd;
    // 绑定嵌套字
    listenfd = socket_bind(IPADDRESS, PORT);
    // 监听嵌套字
    listen(listenfd, LISTENQ);
    // 利用epoll处理读写操作
    do_epoll(listenfd);
    return 0;
}

// 绑定嵌套字
int socket_bind(const char *ip, int port)
{
    int listenfd;
    struct sockaddr_in servaddr;
    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    if (listenfd == -1)
    {
        perror("socket error:");
        exit(1);
    }
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    inet_pton(AF_INET, ip, &servaddr.sin_addr);
    servaddr.sin_port = htons(port);
    if (bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) == -1)
    {
        perror("bind error: ");
        exit(1);
    }
    return listenfd;
}

// 利用epoll处理读写操作
void do_epoll(int listenfd)
{
    int epollfd;
    // 声明一个以结构体epoll_event为元素的数组
    struct epoll_event events[EPOLLEVENTS];
    int ret;
    char buf[MAXSIZE];
    memset(buf, 0, MAXSIZE);
    /*创建一个描述符*/
    epollfd = epoll_create(FDSIZE);
    /*添加监听描述符事件*/
    add_event(epollfd, listenfd, EPOLLIN);
    while (1)
    {
        /*获取已经准备好的描述符事件*/
        ret = epoll_wait(epollfd, events, EPOLLEVENTS, -1);
        handle_events(epollfd, events, ret, listenfd, buf);
    }
    close(epollfd);
}

// 获取到已经准备好的描述符事件后，根据描述符的类型和事件类型进行处理
void handle_events(int epollfd, struct epoll_event *events, int num, int listenfd, char *buf)
{
    int i;
    int fd;
    /*进行选好遍历*/
    for (i = 0; i < num; i++)
    {
        fd = events[i].data.fd;
        /*根据描述符的类型和事件类型进行处理*/
        // 如果描述符是监听描述符且事件可读，就可以接收新的客户端请求
        if ((fd == listenfd) && (events[i].events & EPOLLIN))
            handle_accpet(epollfd, listenfd);
        // 如果事件仅可读，则读取老客户端发送来的包
        else if (events[i].events & EPOLLIN)
            do_read(epollfd, fd, buf);
        // 如果事件为可写，则发送包
        else if (events[i].events & EPOLLOUT)
            do_write(epollfd, fd, buf);
    }
}

void handle_accpet(int epollfd, int listenfd)
{
    int clifd;
    struct sockaddr_in cliaddr;
    socklen_t cliaddrlen;
    clifd = accept(listenfd, (struct sockaddr *)&cliaddr, &cliaddrlen);
    if (clifd == -1)
        perror("accpet error:");
    else
    {
        printf("accept a new client: %s:%d\n", inet_ntoa(cliaddr.sin_addr), cliaddr.sin_port);
        /*添加一个客户描述符和事件*/
        add_event(epollfd, clifd, EPOLLIN);
    }
}

// 服务器会根据客户端发来的内容同样的回包
void do_read(int epollfd, int fd, char *buf)
{
    int nread;
    nread = read(fd, buf, MAXSIZE);
    if (nread == -1)
    {
        // 读操作失败了，关闭相应fd，把读状态事件删除
        perror("read error:");
        close(fd);
        delete_event(epollfd, fd, EPOLLIN);
    }
    else if (nread == 0)
    {
        // 读操作结束了，关闭相应fd，把读状态事件删除
        fprintf(stderr, "client close.\n");
        close(fd);
        delete_event(epollfd, fd, EPOLLIN);
    }
    else
    {
        // 读到数据了
        printf("read message is : %s", buf);
        /*修改描述符对应的事件，由读改为写*/
        modify_event(epollfd, fd, EPOLLOUT);
    }
}

// 写操作处理
void do_write(int epollfd, int fd, char *buf)
{
    int nwrite;
    nwrite = write(fd, buf, strlen(buf));
    if (nwrite == -1)
    {
        // 若写操作失败了，要将其从写事件列表里删除
        perror("write error:");
        close(fd);
        delete_event(epollfd, fd, EPOLLOUT);
    }
    else
        // 若写操作成功了，要继续检测是否有数据，有的话继续写入
        modify_event(epollfd, fd, EPOLLIN);
    memset(buf, 0, MAXSIZE);
}

void add_event(int epollfd, int fd, int state)
{
    struct epoll_event ev;
    ev.events = state;
    ev.data.fd = fd;
    // 添加事件
    epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &ev);
}

void delete_event(int epollfd, int fd, int state)
{
    struct epoll_event ev;
    ev.events = state;
    ev.data.fd = fd;
    // 删除事件
    epoll_ctl(epollfd, EPOLL_CTL_DEL, fd, &ev);
}

void modify_event(int epollfd, int fd, int state)
{
    struct epoll_event ev;
    ev.events = state;
    ev.data.fd = fd;
    // 修改事件
    epoll_ctl(epollfd, EPOLL_CTL_MOD, fd, &ev);
}
